package cn.wy.system.service.impl;

import cn.wy.org.domain.Department;
import cn.wy.system.domain.Menu;
import cn.wy.system.mapper.MenuMapper;
import cn.wy.system.service.MenuService;
import cn.wy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        List<Menu> list = menuMapper.findAll();
       /* List<Menu> menuTree = new ArrayList<>();
         for (Menu menu : list) {
            Long id = menu.getId();
            for (Menu menu1 : list) {
                Long parentId = menu1.getParentId();
                if (parentId == null) {
                    menuTree.add(menu1);
                } else {
                    if (id == parentId) {
                        menu.getChildren().add(menu1);
                    }
                }
            }
        }*/
        Map<Long,Menu> map = new HashMap<>();
        for (Menu menu : list) {
            map.put(menu.getId(),menu);
        }
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : list) {
            if(menu.getParentId()==null){
                menuTree.add(menu);
            }else {
                    Menu parentMenu = map.get(menu.getParentId());
                    parentMenu.getChildren().add(menu);
            }
        }
        return menuTree;

    }
}
